<template>
  <!-- 登录页面主容器 -->
  <div class="main-content">
    <!-- 半透明登录框 -->
    <div class="transparent-box">
      <table>
        <tbody>
          <tr>
            <td>
              <!-- 平台标题 -->
              <h1>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;智慧会议管理平台</h1>
              <p>&nbsp;&nbsp;&nbsp;Smart&nbsp; Conference &nbsp;Management&nbsp; Platform</p>
              <p>&nbsp;</p>
              <p>&nbsp;</p>
              <p>&nbsp;</p>
            </td>
          </tr>
          <tr>
            <td>
              <!-- 登录方式选项卡 -->
              <el-tabs v-model="activeTab" stretch>
                <el-tab-pane label="账户密码登录" name="account"></el-tab-pane>
                <el-tab-pane label="手机号登录" name="phone"></el-tab-pane>
              </el-tabs>

              <!-- 登录表单 -->
              <div>
                <el-form ref="ruleFormRef" style="width: 400px" :model="ruleForm" :rules="rules" label-width="auto">
                  <!-- 账户密码登录表单 -->
                  <template v-if="activeTab === 'account'">
                    <el-form-item style="width: 400px;" label="" prop="accountNumber">
                      <el-input style="height: 40px;" v-model="ruleForm.accountNumber" placeholder="账号" />
                    </el-form-item>
                    <el-form-item label="" prop="password">
                      <el-input v-model="ruleForm.password" style="width: 400px;height: 40px;" type="password"
                        placeholder="密码" show-password />
                    </el-form-item>
                    <!-- 图形验证码 -->
                    <el-form-item label="" prop="password">
                      <el-input style="height: 40px;width: 233px;padding-right: 30px;" placeholder="验证码"
                        v-model="AccountCationCodes.code" />
                      <el-col :span="10">
                        <img :src="ImgCaptcha" alt="" @click="AccountCaptcha">
                      </el-col>
                    </el-form-item>
                  </template>

                  <!-- 手机号登录表单 -->
                  <template v-else>
                    <el-form-item style="width: 400px;" label="" prop="userTelephone">
                      <el-input style="height: 40px;" v-model="ruleForm.userTelephone" placeholder="手机号" />
                    </el-form-item>
                    <el-form-item label="" prop="verifyCode">
                      <el-row gutter="10">
                        <el-col :span="14">
                          <el-input style="height: 40px;" v-model="ruleForm.verificationCode" placeholder="验证码" />
                        </el-col>
                        <el-col :span="10">
                          <el-button style="width:100%" @click="ationCode" size="large">获取验证码</el-button>
                        </el-col>
                      </el-row>
                    </el-form-item>
                  </template>

                  <!-- 登录按钮 -->
                  <el-form-item>
                    <el-button style="width: 400px;height: 40px;" type="primary" @click="submitForm(ruleFormRef)">
                      登录
                    </el-button>
                  </el-form-item>
                </el-form>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script lang="ts" setup>
// 导入Vue相关功能
import { reactive, ref, watch, onMounted } from 'vue'
// 导入Element Plus组件
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
// 导入API接口
import { loginHelper } from '@/api/login'
import { verificationCode, AccountCationCode, AccountCationCodeLogin } from '@/api/cationCode'
// 导入路由
import router from '@/router'
import { useCounterStore } from '@/stores/counter'
import Cookies from 'js-cookie';

// 组件挂载时执行
onMounted(() => {
  // 生成随机数用于验证码ID
  VerificationCodeRandomNumber.value = Math.floor(Math.random() * 1000000).toString()
  // 加载图形验证码
  AccountCaptcha()
  // 从本地存储读取记住的账号密码
  const savedAccount = localStorage.getItem('accountNumber')
  const savedPassword = localStorage.getItem('password')
  if (savedAccount && savedPassword) {
    ruleForm.accountNumber = savedAccount
    ruleForm.password = savedPassword
  }
})

// 响应式数据定义
const activeTab = ref('account') // 当前激活的登录方式选项卡
const AccountCationCodes = ref({ code: "" }) // 图形验证码输入
const ImgCaptcha = ref('') // 图形验证码图片URL
const ruleFormRef = ref<FormInstance>() // 表单引用
const rules = reactive<FormRules>({}) // 表单验证规则
const VerificationCodeRandomNumber = ref('') // 验证码随机数
const route = useCounterStore();//pinia
// 登录表单数据
const ruleForm = reactive({
  "loginState": "", // 登录状态
  "accountNumber": "", // 账号
  "userTelephone": "", // 手机号
  "password": "", // 密码
  "verificationCode": "", // 验证码
})

// 监听登录方式切换
watch(activeTab, () => {
  // 切换登录方式时清空表单
  ruleForm.userTelephone = ''
  ruleForm.password = ''
  ruleForm.accountNumber = ''
}, { deep: true })

// 登录方法
const submitForm = async (formEl: FormInstance | undefined) => {
  // 表单验证
  if (activeTab.value == 'account') {
    if (ruleForm.accountNumber == "") {
      ElMessage.error('请输入账号')
      return
    }
    if (ruleForm.password == "") {
      ElMessage.error('请输入密码')
      return
    }
  }

  try {
    // 调用登录API
    const way = await loginHelper({
      loginState: activeTab.value,
      accountNumber: ruleForm.accountNumber,
      password: ruleForm.password,
      userTelephone: ruleForm.userTelephone,
      verificationCode: ruleForm.verificationCode
    })
    console.log(way.data)
    // 图形验证码
    if (activeTab.value == 'account') {
      // 验证图形验证码
      const AccountCaptchaway = await AccountCationCodeLogin({
        id: VerificationCodeRandomNumber.value,
        code: AccountCationCodes.value.code,
      })
      console.log(!AccountCaptchaway.data)
      if (!AccountCaptchaway.data) {
        ElMessage.error("验证码错误")
        return
      }
    }
    // 登录成功处理
    if (way.data.success) {
      // 记住账号密码      
      ElMessage.success(way.data.message)
      if (true) {
        localStorage.setItem('accountNumber', ruleForm.accountNumber)
        localStorage.setItem('password', ruleForm.password)
        route.userInfo.accountNumber = ruleForm.accountNumber
        route.userInfo.userId = way.data.data.userId
        route.userInfo.userTelephone = way.data.data.userTelephone
        route.userInfo.memberLevel = way.data.data.memberLevel
        route.userInfo.orderRecords = way.data.data.orderRecords
        route.userInfo.availablePoints = way.data.data.availablePoints
        route.userInfo.userTittle = way.data.data.userTittle
        route.userInfo.idNumber = way.data.data.idNumber
        const username = way.data.data.idNumber; // 替换为实际用户名
        Cookies.set('username', username, {
          expires: 7, // 7天后过期
          secure: false, // 仅 HTTPS 传输
          sameSite: 'strict', // 防止 CSRF
          httpOnly: false // 允许前端 JS 读取（默认就是 false）
        });
      }
      // 跳转到首页
      router.push('/HomeView')
    } else {
      ElMessage.error(way.data.message)
    }
  } catch (error) {
    ElMessage.error('登录异常')
  }
}

// 发送手机验证码
const ationCode = async () => {
  if (ruleForm.userTelephone == "") {
    ElMessage.error('请输入手机号')
    return
  }
  const way = await verificationCode({
    phone: ruleForm.userTelephone,
  })
  ElMessage.success(way.data)
}

// 获取图形验证码
const AccountCaptcha = async () => {
  try {
    const way = await AccountCationCode({
      id: VerificationCodeRandomNumber.value,
    })
    //console.log(way)
    // 设置验证码图片URL
    ImgCaptcha.value = way.request.responseURL
  } catch (error) {

    ElMessage.error('图片验证码获取失败')
  }
}
</script>

<style scoped>
/* 主容器样式 */
.main-content {
  margin: 0;
  padding: 0;
  background-image: url('../../assets/loginbackground.png');
  background-size: cover;
  /* 背景图覆盖整个容器 */
  background-position: center center;
  background-repeat: no-repeat;
  background-attachment: fixed;
  /* 固定背景不滚动 */
  min-height: 100vh;
  /* 最小高度为视口高度 */
}

/* 背景图叠加层 */
.main-content::before {
  content: '';
  background-image: url('@/assets/bg.jpg');
  background-size: cover;
  background-position: center;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -1;
  opacity: 0.5;
  /* 半透明效果 */
}

/* 登录框样式 */
.transparent-box {
  position: absolute;
  top: 35%;
  left: 60%;
  width: 30vh;
  height: 30vh;
  margin-top: -100px;
  /* 垂直居中 */
  margin-left: -150px;
  /* 水平居中 */
  background-color: rgba(0, 0, 0, 0);
  /* 透明背景 */
  color: white;
  /* 白色文字 */
  padding: 20px;
  border: 0px;
}
</style>